package com.tnsw.facebookautoliker.helper.command;



import org.json.JSONObject;
import android.content.Context;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Settings;
import com.tnsw.coreutils.MyLog;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.helper.FacebookBGManager;
import com.tnsw.facebookautoliker.helper.FacebookCommandObject;
import com.tnsw.facebookautoliker.helper.GeneralManager;

public class GetSelfInfo extends FacebookCommandObject implements Request.Callback {

	private String tag = "GetSelfInfo";
	
	private FacebookBGManager fbm;
	private DBManager dbm;
	private GeneralManager gm;
	
	private String name = "";
	private String id = "";
	private String email = "";
	private String userName = "";
	
	public GetSelfInfo(Context context) {
		super(context);
		
		this.fbm = FacebookBGManager.getInstance(context);
		this.dbm = DBManager.getInstance(context);
		this.gm = GeneralManager.getInstance();
	}
	
	public String getName() {
		return(this.name);
	}
	
	public String getId() {
		return(this.id);
	}
	
	public String getEmail() {
		return(this.email);
	}
	
	public String getUserName() {
		return(this.userName);
	}
	
	@Override
	protected void handleResult(Response response) {
		super.handleResult(response);
		
		if (response != null) {
			MyLog.d(tag, "handling result of " + response.getRequest().getGraphPath());
			if (response.getError() == null) {
				MyLog.d(tag, "not error");
			
				MyLog.d(tag, "json=" + response.getGraphObject().toString());
				
				JSONObject jo = response.getGraphObject().getInnerJSONObject();
				try {
					this.name = jo.getString("name");
					this.id = jo.getString("id");
					this.userName = jo.getString("username");
					this.email = jo.getString("email");
				} catch (Exception e) {
					MyLog.e(tag, "handleResult - " + e.toString(), e);
				}
				
				this.fbm.updateCommandStatus(this, 200, null);
			} else {
				MyLog.e(tag, "handleResult() - " + response.getError().getException().toString(), response.getError().getException());
				this.fbm.updateCommandStatus(this, 400, response.getError().getException());
			}
			
		} else {
			this.fbm.updateCommandStatus(this, 400, null);
		}
	}
	
	@Override
	public void execute() {
		super.execute();
		
		if (MyLog.isProduction == false) {
			Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
		}
		
		Session session = Session.openActiveSessionFromCache(this.context);
		if (session != null) {
			String path = "me";

			Request req = new Request(session, path, null, HttpMethod.GET);
			
			req.setCallback(this);
			this.standardExecute(req);
		}		
	}

	@Override
	public void onCompleted(Response response) {
		this.handleResult(response);
		
	}

}
